package main

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"go_demo_1/common"
	"go_demo_1/routers"
)

type Option func(*gin.Engine)

var options = []Option{}

// 注册app的路由配置
func Include(opts ...Option) {
	options = append(options, opts...)
}

// 初始化
func Init() *gin.Engine {
	r := gin.New()
	//https://github.com/gin-contrib/sessions
	//store := cookie.NewStore([]byte("secret"))//cookie
		store, _ := redis.NewStore(10, "tcp", "localhost:27379", "", []byte("secret"))   //redis
	//	store := memcached.NewStore(memcache.New("localhost:11211"), "", []byte("secret"))  // memcached
	/*session, err := mgo.Dial("localhost:27017/test") //MongoDB
	if err != nil {
		// handle err
	}
	c := session.DB("").C("sessions")
	store := mongo.NewStore(c, 3600, true, []byte("secret"))*/
	//session中间件的使用
	r.Use(sessions.Sessions("mySessionId", store),common.GinLogger(common.Logger), common.GinRecovery(common.Logger, true))

	for _, opt := range options {
		opt(r)
	}
	return r
}

func initRouter() *gin.Engine {

	Include(
		routers.Index,
		routers.Time,
		routers.Auth,
	) //引入多个路由文件

	r := Init() //初始化gin

	//自动加载静态资源目录
	r.Static("/static", "./static")
	//自动加载模板目录
	r.LoadHTMLGlob("./tpl/*")
	r.GET("/favicon.ico", func(c *gin.Context) {
		c.Header("Cache-Control", "max-age=3153600")
		c.File("./static/favicon.ico")
	})

	return r
}
